package com.kongchengji.zhanguafou.controller;
import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.QuartzDAO;
import com.kongchengji.zhanguafou.domain.QuartzDO;
import com.kongchengji.zhanguafou.domain.Result;
import com.kongchengji.zhanguafou.domain.StationDO;
import com.kongchengji.zhanguafou.service.StationService;
import com.kongchengji.zhanguafou.utils.InfoByCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;

@Controller
public class StationController {
    @Autowired
    private StationService stationService;
    @Autowired
    private QuartzDAO quartzDAO;
    @RequestMapping("/saveStationConfig")
    @ResponseBody
    public Result saveStationConfig(@Validated StationDO stationDO, BindingResult bindingResult){
        stationDO.setOpenId(WxInfo.openId);
        if(bindingResult.hasErrors()){
            for(ObjectError error:bindingResult.getAllErrors()){
                return Result.error(error.getDefaultMessage());
            }
        }
        return stationService.saveStationConfig(stationDO);
    }

    /**
     * 添加监控站点
     * @param code
     * @return
     */
    @RequestMapping("/stationConfig")
    public String stationConfig(@RequestParam String code,Model model){
        //虽然定义了全局的openId,但还是给每个控制器都保存下
        WxInfo.openId = InfoByCodeUtil.getOpenId(code);
        model.addAttribute("isSave",true);
        return "station_config";
    }

    /**
     * 打开服务监控编辑页面
     * @param groupName 分组加域名
     * @return
     */
    @RequestMapping("/openStationEditPage")
    public String openEditPage(String groupName, Model model, HttpServletResponse response) {
        //组装计划任务的唯一标识
        String jobName = groupName + WxInfo.openId;
        Example example = new Example(QuartzDO.class);
        example.createCriteria().andEqualTo("jobName",jobName);
        QuartzDO quartzDO = quartzDAO.selectOneByExample(example);
        String cron = quartzDO.getCronExpression();
        String min = cron.substring("0 0/".length(),cron.indexOf(" ","0 0/".length()));
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        model.addAttribute("quartzDO",quartzDO);
        model.addAttribute("min",min);
        model.addAttribute("isQuartzEdit",true);
        return "station_config";
    }

}
